<template>
  <div class="ticket-detail-list">
    <div class="__top">
      <div class="__lf">
        发票明细行
        <span v-if="isShowDifferent()" class="__ui_different" style="position: relative; top: 2px">
          <el-icon><Warning /></el-icon>
        </span>
      </div>
      <div v-if="!isDisable" class="__rt">
        <span class="__ui_btn" @click="addLine">+新增明细行</span>
        <span class="__ui_line"></span>
        <span class="__ui_btn" @click="deleteLine">删除</span>
      </div>
    </div>
    <el-form ref="detailListForm" :model="form" :rules="rules">
      <PubilcTable :isSlot="true" :table-data="form.detailList" style="width: 100%" :showPageSize="false" @on-selectChange="handleSelectionChange">
        <el-table-column
          type="selection"
          width="55"/>
        <el-table-column
          label="货物或应税劳务名称"
          min-width="120">
          <template #default="scope">
            <el-form-item class="__table_inner_input" :prop="'detailList.' + scope.$index + '.goodsName'" :class="{'is-error': validateTax(scope.row)}">
              <el-input :disabled="isDisable" v-model="scope.row['goodsName']" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          label="金额(不含税)"
          min-width="90">
          <template #default="scope">
            <el-form-item class="__table_inner_input" :prop="'detailList.' + scope.$index + '.excludingTaxAmount'" :class="{'is-error': validateTax(scope.row)}">
              <el-input-number style="width: 100%" :disabled="isDisable" v-model="scope.row['excludingTaxAmount']" :controls="false" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          label="税额"
          min-width="120">
          <template #default="scope">
            <!-- :rules="rules['税额']" -->
            <el-form-item class="__table_inner_input" :prop="'detailList.' + scope.$index + '.taxAmount'" :class="{'is-error': validateTax(scope.row)}">
              <el-input-number style="width: 100%" :disabled="isDisable" v-model="scope.row['taxAmount']" :controls="false" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          label="税率"
          width="80">
          <template #default="scope">
            <!-- :rules="rules['税率']" -->
            <el-form-item class="__table_inner_input" :prop="'detailList.' + scope.$index + '.taxRate'" :class="{'is-error': validateTax(scope.row)}">
              <el-input :disabled="isDisable" v-model="scope.row['taxRate']" oninput="value=value.replace(/[^\d%.]/g,'')" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          v-if="!isDisable"
          label="操作"
          width="65">
          <template #default="scope">
            <el-button type="text" @click="form.detailList.splice(scope.$index, 1)">删除</el-button>
          </template>
        </el-table-column>
      </PubilcTable>
    </el-form>
    <div class="ticket-detail-list-total">
      <div class="__item">
        <span class="__ui_label">明细金额合计</span>
        <span>{{ calcAmount.amount }}</span>
      </div>
      <div class="__item">
        <span class="__ui_label">明细税额合计</span>
        <span>{{ calcAmount.taxAmount }}</span>
      </div>
      <div class="__item">
        <span class="__ui_label">明细价税合计</span>
        <span>{{ calcAmount.totalAmount }}</span>
      </div>
    </div>
  </div>
</template>

<script>
import { computed, reactive, toRefs, watch } from 'vue'
import uniqueId from './unique'
import { ElMessage } from 'element-plus'
import { numAdd, numSub, numMulti, numCheck } from '@/util'
import { Warning } from '@element-plus/icons-vue'
import { checkSingleRow } from '@/components/ScanBillForm/utils/index'
export default {
  components: { Warning },
  props: {
    allListForm: {
      type: Object,
      default: () => {}
    },
    isDisable: {
      type: Boolean,
      default: false
    },
    detailListNew: {
      type: Array,
      default: () => []
    },
    detailListBase: {
      type: Array,
      default: () => []
    },
  },
  setup(props) {
    const handles = {
      validateForm() {
        return new Promise((resolve) => {
          state.detailListForm.validate((res) => {
            console.log(res, '验证')
            resolve(res)
          })
        })
      },
      isShowDifferent() {
        let tarNew = props.detailListNew.map(item => {
          let tar = { ...item }
          delete tar.tarId
          return tar
        })
        let result = false
        if (JSON.stringify(tarNew) !== JSON.stringify(props.detailListBase) && props.isDisable && props.allListForm.inputBy == 1) {
          result = true
        }
        return result
      },
      setUniqueId (arr) {
        arr.forEach(item => {
          item.tarId = uniqueId()
        })
        return arr
      },
      handleSelectionChange(list) {
        state.selectList = list
      },
      addLine() {
        state.form.detailList.push({
          'goodsName': '',
          'excludingTaxAmount': '',
          'taxAmount': '',
          'taxRate': '',
          'invoiceId': props.allListForm ? props.allListForm.id: '' , 
          tarId: uniqueId()
        })
      },
      deleteLine() {
        if (state.selectList.length <= 0) {
          ElMessage.warning('请选择明细！')
          return false
        }
        state.form.detailList = state.form.detailList.filter(item => {
          let result = true
          state.selectList.forEach(childItem => {
            if (item.tarId == childItem.tarId) {
              result = false
            }
          })
          return result
        })
      },
      validateTax (row) {
        let result = false
        if (row && row.excludingTaxAmount && row.taxAmount && row.taxRate) {
          result = checkSingleRow(row)
        }
        return result
      }
    }
    const state = reactive({
      detailListForm: null,
      rules: {
        'goodsName': [{ required: true, message: '请输入货物或应税劳务、服务名称', trigger: 'blur' },],
        'excludingTaxAmount': [{ required: true, message: '请输入金额', trigger: 'blur' },],
        'taxAmount': [{ required: true, message: '请输入税额', trigger: 'blur' },],
        'taxRate': [{ required: true, message: '请输入税率', trigger: 'blur' },]
      },
      form: {
        detailList: handles.setUniqueId(props.detailListNew)
      },
      selectList: []
    })
    const calcAmount = computed(() => {
      let amount = 0
      let taxAmount = 0
      state.form.detailList && state.form.detailList.forEach(item => {
        amount = numAdd(amount, numCheck(item['excludingTaxAmount'] || 0))
        taxAmount = numAdd(taxAmount, numCheck(item['taxAmount'] || 0))
      })
      let totalAmount = numAdd(amount, taxAmount)
      totalAmount = totalAmount ? totalAmount.toFixed(2): totalAmount
      return {
        amount,
        taxAmount,
        totalAmount: totalAmount
      }
    })
    // watch(() => props.detailListNew, (newVal) => {
    //   state.form.detailList = handles.setUniqueId(newVal)
    //   console.log(state.form.detailList, 'state.form.detailList')
    // }, {
    //   immediate: true,
    //   deep: true
    // })
    return {
      ...toRefs(state),
      ...handles,
      calcAmount
    }
  }
}
</script>
<style lang="scss" scoped>
.ticket-detail-list{
  padding: 5px 0;
  .__top{
    display: flex;
    align-items: center;
    justify-content: space-between;
    .__lf{
      font-size: 14px;
      font-weight: 500;
      color: #6B728A;
      line-height: 32px;
    }
    .__rt{
      display: flex;
      align-items: center;
      .__ui_btn{
        font-size: 14px;
        color: #1890FF;
        cursor: pointer;
      }
      .__ui_line{
        margin: 0 12px;
        display: inline-block;
        width: 1px;
        height: 22px;
        background:#F0F0F0;
      }
    }
  }
  &-total{
    position: relative;
    top: -3px;
    display: flex;
    flex-wrap: wrap;
    border-bottom: 1px solid #D9D9D9;
    .__item{
      padding: 4px 8px;
      width: 50%;
      display: flex;
      font-size: 14px;
      color: #595959;
      border: 1px solid #D9D9D9;
      box-sizing: border-box;
      &:last-child{
        border-top: none;
        border-right: none;
        border-bottom: none
      }
      .__ui_label{
        margin-right: 10px;
        font-size: 14px;
        font-weight: 500;
        color: #6B728A;
      }
    }
  }
  :deep(.el-table th.el-table__cell > .cell, .el-form-item__label){
    font-size: 14px!important;
    color: rgba(107, 114, 138, 1)!important;
  }
  :deep(.el-table .cell){
    padding: 3px 16px;
    // height: 61px;
  }
  :deep(.el-form-item__content){
    flex-direction: column;
    justify-content: flex-start;
    align-items: flex-start;
  }
  :deep(.el-form-item__error){
    position: relative;
    top: 0;
  }
  .__table_inner_input{
    margin-bottom: 0;
  }
  .is-error{
    :deep(.el-input__inner){
      // box-shadow: 0 0 0 1px #E6A23C inset;
      color: red;
    }
  }
}
</style>